package com.health.ts.controller;

import java.beans.PropertyEditorSupport;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.health.ts.constant.FrontPage;

import cn.hutool.core.convert.Convert;

/**
 * 基础类，所有controller都应该继承这个类
 */
public class BaseController {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	public static final String TEXT_UTF8 = "text/html;charset=UTF-8";
	public static final String JSON_UTF8 = "application/json;charset=UTF-8";
	public static final String XML_UTF8 = "application/xml;charset=UTF-8";

	/**
	 * 页面重定向
	 * 
	 * @param format
	 * @param arguments
	 * @return
	 */
	protected String redirect(String format, Object... arguments) {
		return new StringBuffer("redirect:").append(MessageFormat.format(format, arguments)).toString();
	}

	/**
	 * 取得FrontPage中参数
	 * 
	 * @param page
	 * @param paramName
	 * @return
	 */
	protected String getParam(FrontPage page, String paramName) {
		String paramValue = "";
		Map<String, Object> params = page.getParams();
		if (params != null && params.get(paramName)!=null) {
			paramValue = params.get(paramName).toString();
		}
		return StringUtils.isNotEmpty(paramValue) ? paramValue : "";
	}
	
	 /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder){
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport(){
            @Override
            public void setAsText(String text){
                setValue(Convert.toDate(text));
            }
        });
    }
}
